<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <div>
        <el-button
          type="primary"
          size="default"
          icon="ele-Plus"
          @click="offDialog"
          >添加</el-button
        >
      </div>
    </template>
    <!-- 表格 -->
    <!--
          data    用于表格展示的数据
          type    列类型
          label   列标题
          prop    获取数据中对应属性标识
          row     作用域插槽中的当前行的数据
         -->
    <el-table border stripe :data="ProductList" v-loading="tableLoading">
      <el-table-column type="index" width="90" label="序号" />
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌logo">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" width="100" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            icon="ele-EditPen"
            type="warning"
            size="small"
            @click="offUpdataDialog(row)"
            >修改</el-button
          >

          <el-popconfirm
            title="确认要删除吗?"
            icon="ele-Delete"
            @confirm="deleteTm(row.id)"
          >
            <template #reference>
              <el-button icon="ele-Delete" type="danger" size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!--
       current-page  当前页
       pagesize      每页条数
       page-sizes    选择展示每页条数
       layout        分页器功能布局
       total         总条数
    -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      layout="  prev, pager, next,sizes,total"
      :total="total"
      :style="{ marginTop: '20px' }"
    />

    <!-- 添加对话框 -->

    <!--
      dialogVisible    是否显示对话框
      title            对话框标题(具名插槽-header)
      before-close     关闭前的回调函数
     -->
    <el-dialog v-model="dialogVisible" width="30%">
      <template #header>
        <div>
          <h4>{{ `${tmInfo.id ? "修改" : "新增"}` }}品牌</h4>
        </div>
      </template>

      <el-form
        ref="ruleFormRef"
        label-width="80px"
        :inline="false"
        :model="tmInfo"
        :rules="rules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmInfo.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmInfo.logoUrl" :src="tmInfo.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="default" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="tradmark"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "ProductList",
});
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import {
  reqProductList,
  reqAddTrademark,
  reqUpdataTrademark,
  type ProductItemType,
  reqDeleteTrademark,
} from "@/api/product";
import type { ProductType } from "@/api/product";
import { ElMessage, type UploadProps } from "element-plus";

const currentPage = ref(1); //当前页
const pageSize = ref(3); //每页展示条数
const total = ref(0); // 总条数

// 用于存放品牌数据的数组
let ProductList = ref<ProductType>([]);

// 控制table的loading状态
let tableLoading = ref(false);

// 初始化品牌分页数据
onMounted(async () => {
  getProductList();
});

// 请求分页列表数据的方法
const getProductList = async () => {
  // 显示loading
  tableLoading.value = true;
  const re = await reqProductList(currentPage.value, pageSize.value);
  // 保存数据
  ProductList.value = re.records;
  total.value = re.total;
  // 关闭loading
  tableLoading.value = false;
};

// 监听页码发生变化
watch([currentPage, pageSize], () => {
  // 发生变化则请求数据
  getProductList();
});

// 添加对话框功能

// 添加对话框显示
const dialogVisible = ref(false);
// 当前开发环境的api地址
const baseUrl = import.meta.env.VITE_API_URL;

// 自定义校验规则的函数
const checkTmName = (rule: any, value: any, callback: any) => {
  // if (value.length <= 5 && value.length >= 2) {
  //   callback("输入的长度在2-5之间");
  // } else {
  //   callback();
  // }
  return value.length <= 5 && value.length >= 2;
};

// 品牌数据校验规则
const rules = reactive({
  tmName: [
    { required: true, message: "品牌名称不能为空！", trigger: "blur" },
    { validator: checkTmName, message: "品牌名称2-5之间", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "品牌logo不能为空！", trigger: "blur" }],
});

// // 图片地址
// const imageUrl = ref("");

// // 品牌名称
// const tmName = ref("");

// 品牌数据
const tmInfo = ref<ProductItemType>({
  logoUrl: "",
  tmName: "",
});

// 表单元素ref
const ruleFormRef = ref();

// 打开新增品牌窗口
const offDialog = () => {
  // 显示对话框
  dialogVisible.value = true;

  // 清空校验规则
  ruleFormRef.value?.clearValidate();
  // 重置数据
  tmInfo.value = {
    logoUrl: "",
    tmName: "",
  };
};

// 上传成功的回调函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // console.log(response, uploadFile);

  tmInfo.value.logoUrl = response.data;
};

// 上传之前的回调函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("品牌图片只能是jpg格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("品牌图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 点击确定后品牌信息提交功能
const tradmark = async () => {
  // console.log(tmInfo.value);

  try {
    await ruleFormRef.value.validate();
  } catch {
    ElMessage.error("检查添加规则");
    return;
  }

  // 判断是否有id  如果有则是修改商品 如果没有就是新增品牌
  if (tmInfo.value.id) {
    // 发送修改商品请求
    await reqUpdataTrademark(tmInfo.value);
    // 修改成功提示
    ElMessage.success("修改品牌成功!");
  } else {
    // 请求新增品牌数据
    await reqAddTrademark(tmInfo.value);

    // 新增成功提示
    ElMessage.success("新增品牌成功!");
  }

  //关闭新增对话框
  dialogVisible.value = false;

  // 重新请求数据
  getProductList();
};
// 点击修改按钮事件
const offUpdataDialog = (row: ProductItemType) => {
  // 打开修改对话框
  dialogVisible.value = true;
  // console.log(row);
  tmInfo.value = { ...row };
  // 清空校验规则
  ruleFormRef.value?.clearValidate();
};

// 点击删除按钮事件
const deleteTm = async (id: number) => {
  // 发送删除请求
  await reqDeleteTrademark(id);
  // 重新发送请求
  getProductList();
  // 提示删除成功
  ElMessage.success("删除成功!");
};
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
